package com.trytech.mongoocrawler.server.common.db;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.trytech.mongoocrawler.server.common.exception.DataSourceInitException;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Druid连接Mysql的连接池
 */
public class MySqlDruidDataSource extends CrawlerDataSource {
    private DruidDataSource dataSource;
    private Connection conn;
    @Override
    public void init() throws DataSourceInitException {
        try {
            dataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(propertiesMap);
        } catch (Exception e) {
            throw new DataSourceInitException("Mysql DataSource initialization get failed!");
        }
    }

    private Connection getConnection() throws DataSourceInitException {
            try {
                conn = dataSource.getConnection();
            } catch (SQLException e) {
                throw new DataSourceInitException("Mysql DataSource initialization get failed!");
            }
        return conn;
    }
    @Override
    public void destory() {
        if(dataSource != null){
            dataSource.close();
        }
    }

    public void insert(String sql){
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            connection = getConnection();
            statement = connection.prepareStatement(sql);
            statement.execute();

        } catch (DataSourceInitException | SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                statement.close();
                connection.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
}
